<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use think\Env;
use think\Log;
use AstroTool\Cache\CacheManage;

class ZlFeedbackQuestionInfo extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_feedback_question_info';

    protected $cacheModel = 'feedback.question_send_msg_info';

    /**
     * 意见反馈会话回复
     * @param int $fqId
     * @param array $data
     * @return mixed|object|array|bool|int|\stdClass|float|null
     */
    public function saveData(int $fqId, array $data)
    {
        try
        {
            $this->save($data);
            //  更新有新消息
            $this->listDataAdd($fqId, [$this->id => $this->id]);

            if ($data['reply_attr'] === 1)
            {
                (new ZlFeedbackQuestion())->save(['admin_has_msg' => 1, 'last_reply_time' => $data['create_time'], 'update_time' => $data['create_time']], ['id' => $fqId]);
            } else
            {
                (new ZlFeedbackQuestion())->save(['user_has_msg' => 1, 'update_time' => $data['create_time']], ['id' => $fqId]);
            }
        }
        catch (\Exception $e)
        {
            Log::write('意见反馈会话回复失败：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return false;
        }
        return $this->id;
    }

    /**
     * 系统自动回复
     * @param int $fqid
     * @return bool
     */
    public function systemReply(int $fqid): bool
    {
        try
        {
            $data = [
                'fq_id' => $fqid,
                'reply_attr' => 0,
                'uid' => 0,
                'aid' => 0,
                'content' => '亲爱的小行星，您反馈的问题我们已经收到了，还请您稍作等待，我们会尽快给您回复哦~
工作时间：工作日10:00至18:00',
                'content_type' => 1,
                'create_time' => time()
            ];

            return $this->saveData($fqid, $data);
        }
        catch (\Exception $e)
        {
            Log::write('意见反馈自动回复失败：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return false;
        }
    }

    /**
     * 获取会话列表
     * @param int $fqid
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getReplyList(int $fqid, int $page, int $limit = 10): array
    {
        $dataList = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $fqid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($fqid, $page, $limit)
            {
                if ($isCache)
                { // 开启了缓存
                    return $this->getInfoByIdsInData($ids, [$fqid], $sortType);
                } else
                { // 没开启缓存
                    return $this->getPaginateInData([$fqid, $page, $limit], $sortType);
                }
            }, 'id', [], 0);

        if (isset($dataList['data']))
        {
            $d = [];
            $host = Env::get('host.photo');
            $userAvatar = $host . config('feedback.user_avatar');
            $adminAvatar = $host . config('feedback.admin_avatar');

            foreach ($dataList['data'] as $item)
            {
                $contentType = (int)$item['content_type'];
                $replyAttr = (int)$item['reply_attr'];

                $d[] = [
                    'id' => (int)$item['id'],
                    'avatar' => $replyAttr === 1 ? $userAvatar : $adminAvatar,
                    'content' => $contentType === 1 ? $item['content'] : $host . $item['content'],
                    'content_type' => $contentType,
                    'create_time' => date('Y-m-d', $item['create_time']),
                    'isself' => $replyAttr === 1 ? 1 : 0
                ];
            }

            $dataList['data'] = $d;
        }

        return $dataList;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where(['fq_id' => $type[0]]);
            }
            $data = $this->order("id {$sortType}")
                ->column('fq_id,reply_attr,uid,aid,content,content_type,create_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }


    /**
     * 未开启缓存从数据库获取分页数据
     * @param array $type 分页数据状态
     * @param string $sortType 排序方式
     * @return array
     */
    public function getPaginateInData($type, $sortType)
    {
        try
        {
            $data = $this->order("id {$sortType}")->where(['fq_id' => $type[0]])
                ->field('id,fq_id,reply_attr,uid,aid,content,content_type,create_time')
                ->paginate($type[2], true, ['page' => $type[1]])->toArray();

            return $data;
        }
        catch (\Exception $e)
        {
            return [];
        }
    }

    /**
     * 获取最新回复消息
     * @param int $fqid
     * @param int $oldMsgID
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getNewData(int $fqid, int $oldMsgID): array
    {
        $cacheModel = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $fqid);

        $cacheKey = $cacheModel->cacheKey['list'];
        $redis = $cacheModel->redisHandler;

        if ($redis->exists($cacheKey))
        {   // 有缓存查询
            $ids = $redis->zRevRangeByScore($cacheKey, '+inf', '(' . $oldMsgID);
            if ($ids)
            {
                $replyDataList = $this->batchGetInfoByIds($ids, ['id', 'reply_attr', 'content', 'content_type', 'create_time']);

                $resData = [];
                foreach ($ids as $id)
                {
                    if (!isset($replyDataList[$id])) continue;

                    $contentType = (int)$replyDataList[$id]['content_type'];
                    $replyAttr = (int)$replyDataList[$id]['reply_attr'];
                    $host = Env::get('host.photo');
                    $userAvatar = $host . config('feedback.user_avatar');
                    $adminAvatar = $host . config('feedback.admin_avatar');

                    $resData[] = [
                        'id' => (int)$replyDataList[$id]['id'],
                        'avatar' => $replyAttr === 1 ? $userAvatar : $adminAvatar,
                        'content' => $contentType === 1 ? $replyDataList[$id]['content'] : $host . $replyDataList[$id]['content'],
                        'content_type' => $contentType,
                        'create_time' => date('Y-m-d', $replyDataList[$id]['create_time']),
                        'isself' => $replyAttr === 1 ? 1 : 0
                    ];
                }

                return $resData;
            } else
            {
                return [];
            }
        } else
        {   // 缓存不存在
            $data = $this->where('fq_id', $fqid)->where('id', '>', $oldMsgID)->field('id,fq_id,reply_attr,uid,aid,content,content_type,create_time')->order('id desc')->select();
            if ($data)
            {
                $resData = [];
                foreach ($data as $dataItem)
                {
                    $contentType = (int)$dataItem['content_type'];
                    $replyAttr = (int)$dataItem['reply_attr'];
                    $host = Env::get('host.photo');
                    $userAvatar = $host . config('feedback.user_avatar');
                    $adminAvatar = $host . config('feedback.admin_avatar');

                    $resData[] = [
                        'id' => (int)$dataItem['id'],
                        'avatar' => $replyAttr === 1 ? $userAvatar : $adminAvatar,
                        'content' => $contentType === 1 ? $dataItem['content'] : $host . $dataItem['content'],
                        'content_type' => $contentType,
                        'create_time' => date('Y-m-d', $dataItem['create_time']),
                        'isself' => $replyAttr === 1 ? 1 : 0
                    ];
                }
                return $resData;
            }

            return [];
        }
    }
}
